package com.fpf.lab01_basics;

public class Demo6_Synchronized {

    private int count = 0;

    // 通过synchronized关键字确保了每一次只能有一个线程执行该方法,处理两个线程单独资源竞争问题
    public synchronized void inc() {
        count++;
    }
    //public  void inc() {
    //   count++;
    //}

    public static void main(String[] args) throws InterruptedException {
        Demo6_Synchronized obj = new Demo6_Synchronized();
        Runnable tesk = () -> {
            for (int i = 0; i < 500_00; i++) obj.inc();
        };
        Thread t1 = new Thread(tesk);
        Thread t2 = new Thread(tesk);
        t1.start();
        t2.start();
        // 让主线程等待子线程计算结束后再输出结果
        t1.join();
        t2.join();
        System.out.println("count: " + obj.count);
    }
}
